package com.example.manpower.Controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.manpower.Dto.UserExport;
import com.example.manpower.Entity.User;
import com.example.manpower.Mapper.UserMapper;
import com.example.manpower.Server.UserService;
import com.example.manpower.Util.Result;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    //通过id查询员工信息
    @GetMapping("/selectById")
    public Result selectById(User user){
        return userService.selectById(user);
    }

    //增加员工信息
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        return userService.add(user);
    }

    //修改员工信息
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        return userService.update(user);
    }

    //逻辑删除员工信息
    @DeleteMapping("/delete")
    public Result delete(User user) {
        System.out.println("----------------------------------------"+"User");
        System.out.println(user);
        return userService.delete(user);
    }

    //分页查询员工信息
    @GetMapping("/selectPage")
    public Result selectPage(User user){
        return userService.selectPage(user);
    }

    // 查询员工总人数
    @GetMapping("/totalEmployees")
    public Result getTotalEmployees() {
        return userService.countTotalEmployees();
    }

    // 查询部门总数
    @GetMapping("/totalDepartments")
    public Result getTotalDepartments() {
        return userService.countTotalDepartments();
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据\
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status", 1);
        List<User> list = userService.list(queryWrapper);

        // 创建要导出的 DTO 列表
        List<UserExport> exportList = list.stream().map(user -> {
            UserExport dto = new UserExport();
            dto.setUserId(user.getUserId());
            dto.setUserName(user.getUserName());
            dto.setUserSex(user.getUserSex());
            dto.setUserAge(user.getUserAge());
            dto.setAddress(user.getAddress());
            dto.setUserCarid(user.getUserCarid());
            dto.setPhone(user.getPhone());
            dto.setEmail(user.getEmail());
            dto.setNation(user.getNation());
            dto.setPositionName(user.getPositionName());
            dto.setPostitionId(user.getPostitionId());
            dto.setDepartmentId(user.getDepartmentId());
            dto.setUserSalary(user.getUserSalary());
            dto.setEntryTime(user.getEntryTime());
            dto.setResignationTime(user.getResignationTime());
            dto.setCreateTime(user.getCreateTime());
            dto.setUpdateTime(user.getUpdateTime());

            // 设置其他需要导出的字段
            return dto;
        }).collect(Collectors.toList());

        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("userId", "id");
        writer.addHeaderAlias("userName", "姓名");
        writer.addHeaderAlias("userSex", "性别");
        writer.addHeaderAlias("userAge", "年龄");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("userCarid", "身份证号");
        writer.addHeaderAlias("phone", "手机号");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("nation", "民族");
        writer.addHeaderAlias("positionName", "职位名称");
        writer.addHeaderAlias("postitionId", "职位id");
        writer.addHeaderAlias("departmentId", "部门id");
        writer.addHeaderAlias("userSalary", "薪资");
        writer.addHeaderAlias("entryTime", "入职时间");
        writer.addHeaderAlias("resignationTime", "离职时间");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("updateTime", "更新时间");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(exportList, true);


        // 获取工作表
        Sheet sheet = writer.getSheet();

        // 设置列宽
        // 例如，设置第1列的默认宽度为20个字符宽度
        sheet.setColumnWidth(13, 20 * 256);
        sheet.setColumnWidth(14, 20 * 256);
        sheet.setColumnWidth(15, 20 * 256);
        sheet.setColumnWidth(16, 20 * 256);

        // 创建时间格式
        CellStyle dateStyle = writer.getWorkbook().createCellStyle();
        CreationHelper createHelper = writer.getWorkbook().getCreationHelper();
        dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        // 应用时间格式
        for (int i = 0; i < exportList.size(); i++) {
            UserExport userExport = exportList.get(i);
            Row row = writer.getSheet().getRow(i + 1);
            if (row == null) {
                row = writer.getSheet().createRow(i + 1);
            }
            Cell entryTimeCell = row.createCell(13); // 假设入职时间在第13列
            entryTimeCell.setCellValue(userExport.getEntryTime());
            entryTimeCell.setCellStyle(dateStyle);

            Cell resignationTimeCell = row.createCell(14); // 假设离职时间在第15列
            resignationTimeCell.setCellValue(userExport.getResignationTime());
            resignationTimeCell.setCellStyle(dateStyle);

            Cell createTimeCell = row.createCell(15); // 假设创建时间在第18列
            createTimeCell.setCellValue(userExport.getCreateTime());
            createTimeCell.setCellStyle(dateStyle);

            Cell updateTimeCell = row.createCell(16); // 假设更新时间在第19列
            updateTimeCell.setCellValue(userExport.getUpdateTime());
            updateTimeCell.setCellStyle(dateStyle);
        }

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("员工信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 导入接口
     *
     * @param file 导入文件
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUserName(row.get(0).toString());
            user.setUserSex(row.get(1).toString());
            user.setUserAge(Integer.valueOf(row.get(2).toString()));
            user.setAddress(row.get(3).toString());
            user.setUserCarid(row.get(4).toString());
            user.setPhone(row.get(5).toString());
            user.setEmail(row.get(6).toString());
            user.setNation(Integer.valueOf(row.get(7).toString()));
            user.setPositionName(row.get(8).toString());
            user.setPostitionId(Integer.valueOf(row.get(9).toString()));
            user.setDepartmentId(Integer.valueOf(row.get(10).toString()));
            user.setUserSalary(BigDecimal.valueOf(Long.parseLong(row.get(11).toString())));
            users.add(user);
        }
        userService.saveBatch(users);
        return true;
    }

}
